import os
import shutil
from pathlib import Path
from typing import List, Dict, Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

router = APIRouter(prefix="/api", tags=["move-files"])

class MoveRequest(BaseModel):
    source: str
    destination: str

class MoveFilesRequest(BaseModel):
    moves: List[MoveRequest]
    createDirIfNotExists: bool = False

class MoveFilesResponse(BaseModel):
    success: bool
    movedCount: int = 0
    failedCount: int = 0
    errors: List[str] = []

@router.post("/move-files")
async def move_files(request: MoveFilesRequest) -> MoveFilesResponse:
    """
    根据报告执行文件移动操作
    纯粹的文件系统操作，不涉及数据库
    """
    response = MoveFilesResponse(success=True, movedCount=0, failedCount=0, errors=[])
    
    if not request.moves:
        response.errors.append("没有需要移动的文件")
        response.success = False
        return response
    
    for move in request.moves:
        try:
            source_path = Path(move.source)
            dest_path = Path(move.destination)
            
            # 检查源文件是否存在
            if not source_path.exists():
                response.errors.append(f"源文件不存在: {move.source}")
                response.failedCount += 1
                continue
            
            # 检查是否是文件
            if not source_path.is_file():
                response.errors.append(f"源路径不是文件: {move.source}")
                response.failedCount += 1
                continue
            
            # 检查目标目录是否存在，如果不存在则创建
            dest_dir = dest_path.parent
            if not dest_dir.exists():
                if request.createDirIfNotExists:
                    try:
                        dest_dir.mkdir(parents=True, exist_ok=True)
                    except Exception as e:
                        response.errors.append(f"创建目标目录失败 {dest_dir}: {str(e)}")
                        response.failedCount += 1
                        continue
                else:
                    response.errors.append(f"目标目录不存在: {dest_dir}")
                    response.failedCount += 1
                    continue
            
            # 执行文件移动
            try:
                shutil.move(str(source_path), str(dest_path))
                response.movedCount += 1
            except Exception as e:
                response.errors.append(f"移动文件失败 {move.source} -> {move.destination}: {str(e)}")
                response.failedCount += 1
                
        except Exception as e:
            response.errors.append(f"处理文件移动时发生错误: {str(e)}")
            response.failedCount += 1
    
    # 如果有任何失败，标记为部分失败
    if response.failedCount > 0:
        response.success = response.movedCount > 0  # 如果有成功的，就是部分成功
    
    return response